<?php
declare (strict_types=1);

namespace app\command;

use app\common\lib\ZhyxBeanstalkd;
use app\impl\EmployeeGranule;
use app\impl\SimpleFactory;
use Pheanstalk\Exception\ClientException;
use Pheanstalk\Exception\ConnectionException;
use Pheanstalk\Exception\ServerException;
use think\console\Command;
use think\console\Input;
use think\console\input\Argument;
use think\console\input\Option;
use think\console\Output;
use think\Exception;
use think\facade\Log;

class WatchClearData extends Command
{
    protected function configure(): void
    {
        // 指令配置
        $this->setName('watchClearData')
            ->setDescription('消费者队列');
    }

    protected function execute(Input $input, Output $output)
    {
        ini_set("default_socket_timeout", "604800");
        ini_set("memory_limit", "1G");
        while (true) {
            $beansTalk = ZhyxBeanstalkd::getInstance()->beansTalk;
            $job = null;
            try {
                $job = $beansTalk
                    ->watch("employeeGranule")
                    ->ignore("default")->reserve();
                if ($job !== false) {
                    $output->writeln("收到任务:" . $job->getData());
                    $data = json_decode($job->getData(), true);
                    $output->writeln("任务名称" . $data["tubeName"]);
                    $task = SimpleFactory::getTask($data["tubeName"]);
                    $result = $task->run($data, (string)$job->getId());
                    $output->writeln("任务返回:" . $result);
                    if ($result === true) {
                        $beansTalk->delete($job);
                    }
                }
                sleep(1);
            } catch (ClientException $clientException) {
                Log::error($clientException->getMessage());
            } catch (ServerException $serverException) {
                Log::error($serverException->getMessage());
            } catch (ConnectionException $connectionException) {
                Log::error($connectionException->getMessage());
            } catch (\Exception $exception) {
                $output->writeln("任务异常:" . $exception->getMessage() . $exception->getFile() . $exception->getCode());
                $beansTalk->delete($job);
                Log::error($exception->getMessage());
            }
        }
    }


}
